package com.sxt.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxt.entity.Order;
import com.sxt.entity.OrderItem;
import com.sxt.entity.OrderSettlement;
import com.sxt.mapper.OrderItemMapper;
import com.sxt.mapper.OrderMapper;
import com.sxt.mapper.OrderSettlementMapper;
import com.sxt.model.ShopCartItem;
import com.sxt.service.ProdService;
import com.sxt.service.SkuService;

@Component
public class OrderCancelListener implements MessageListener{

	@Autowired
	private OrderSettlementMapper orderSettlementMapper ;

	@Autowired
	private OrderMapper orderMapper ;

	@Autowired
	private OrderItemMapper orderItemMapper ;

	@Reference(check = false)
	private SkuService skuService ;

	@Reference(check = false)
	private ProdService prodService ;

	@JmsListener(destination = "order.delay.queue")
	public void onMessage(Message message) { // 这个消息，一般30min 后才过来
		TextMessage textMsg= (TextMessage) message ;
		try {
			String orderSn = textMsg.getText(); //
			OrderSettlement orderSettlement = orderSettlementMapper.selectOne(new LambdaQueryWrapper<OrderSettlement>().eq(OrderSettlement::getOrderNumber, orderSn));
			Integer status = orderSettlement.getPayStatus();
			if(status!=null && status.equals(1)) { // 订单支付了
				return ;
			}else { // 订单没有支付
				orderSettlement.setIsClearing(0) ;
				Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderSn));
				order.setStatus(6) ; // 订单失败
				order.setCloseType(1) ;
				order.setIsPayed(false) ;
				orderSettlementMapper.updateById(orderSettlement) ;
				orderMapper.updateById(order) ;
				// 回滚库存数据
				rollbackStock(orderSn);
			}


		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	private void rollbackStock(String orderSn) {
		List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderSn)) ;
		// prodStock
		// skuStock
		List<ShopCartItem> cartItems = new ArrayList<>(orderItems.size());
		for (OrderItem orderItem : orderItems) {
			ShopCartItem shopCartItem = new ShopCartItem();
			shopCartItem.setProdId(orderItem.getProdId()); // 商品的库存 == 多个sku 相加
			Integer prodCount = orderItem.getProdCount()*(-1);
			shopCartItem.setProdCount(prodCount);
			shopCartItem.setSkuId(orderItem.getSkuId());
			shopCartItem.setProdCount(prodCount);
			cartItems.add(shopCartItem) ;
		}
		// 回滚库存
		skuService.decrStock(cartItems);
		prodService.decsStock(cartItems);
		// redis的库存也需要回滚一下
	}

}
